package com.kb.controller;


import cn.hutool.http.HttpUtil;
import com.kb.common.ApiResponse;
import com.kb.dto.InvoiceSearchDTO;
import com.kb.dto.crm.CrmDocumentEntity;
import com.kb.dto.other.CrmWaitInvoiceData;
import com.kb.dto.other.InvoiceSearch;
import com.kb.entity.crm.Invoice;
import com.kb.service.K3Service;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * crm to k3 invoicing interface
 */
@RestController
@RequestMapping("k3")
public class K3Controller {

    @Resource
    private K3Service k3Service;

    /**
     * 从局域网路径复制文件到本地
     *
     * @param networkPath 根据id获取文件  : d972e7ad-8b22-4875-b66c-76fba3291476
     * @param
     */
    @GetMapping("/getFileFromLAN")
    public ResponseEntity<byte[]> getFileFromLAN(String networkPath) throws IOException {
        try {
            CrmDocumentEntity crmDocumentEntity = k3Service.queryDocument(networkPath);
            if (crmDocumentEntity != null) {
                // url 转换
                String yearPath = crmDocumentEntity.getYearPath();
                String monthPath = crmDocumentEntity.getMonthPath();
                String dayPath = crmDocumentEntity.getDayPath();
                networkPath = "\\\\192.168.10.12\\attach\\crm\\files\\Invoice\\" + yearPath + "\\" + monthPath + "\\" + dayPath + "\\" + crmDocumentEntity.getAttachId() + "";

                Path path = Paths.get(networkPath);
                byte[] fileBytes = Files.readAllBytes(path);
                // 构建响应头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentDispositionFormData("attachment", crmDocumentEntity.getAttachId());
                return ResponseEntity.ok()
                        .headers(headers)
                        .body(fileBytes);
            }

        } catch (IOException e) {
            System.err.println("读取文件失败: " + e.getMessage());
            throw new RuntimeException("文件读取失败", e);
        }
        return null;
    }

    /**
     * 获取待开票列表
     *
     * @param invoiceSearchDTO
     */
    @PostMapping("/queryWaitInvoiceList")
    public ApiResponse<List<CrmWaitInvoiceData>> queryWaitInvoiceList(@RequestBody InvoiceSearch invoiceSearchDTO) {
        return ApiResponse.success(k3Service.queryWaitInvoiceList(invoiceSearchDTO));
    }
    /**
     * 回写开票信息
     *
     * @param invoice
     */
    @PostMapping("/updateInvoiceInfo")
    public ApiResponse<Boolean> updateInvoiceInfo(@RequestBody Invoice invoice) {
        return ApiResponse.success(k3Service.updateInvoiceInfo(invoice));
    }
}
